package com.tss.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tss.mapper.UserMapper;
import com.tss.pojo.User;
import com.tss.pojo.UserExample;
import com.tss.pojo.UserExample.Criteria;
import com.tss.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public boolean addUser(User user) {
		if(user==null){
			return false;
		}
		User u = findUser(user);
		if(u!=null){
			return false;
		}
		user.setValidate(true);
		userMapper.insert(user);
		
		return true;
	}

	@Override
	public boolean deleteUser(Long id) {
		if(id==null){
			return false;
		}
		User user = findUser(id);
		if(user==null){
			return false;
		}
		user.setValidate(false);
		updateUser(user);
		return true;
	}

	@Override
	public boolean updateUser(User user) {
		if(user == null||user.getId()==null){
			return false;
		}
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(user.getId());
		userMapper.updateByExample(user, example);
		return true;
	}

	@Override
	public User findUser(Long id) {
		if(id==null){
			return null;
		}
		User user = userMapper.selectByPrimaryKey(id);
		if(user==null||user.getValidate()==false){
			return null;
		}
		return user;
	}
	
	@Override
	public User findUser(User user) {
		
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		if(user.getId()!=null){
			User uu= userMapper.selectByPrimaryKey(user.getId());
			if(uu.getValidate()){
				return uu;
			}else{
				return null;
			}
			
		}
		if(user.getNickname()!=null){
			criteria.andNicknameEqualTo(user.getNickname());
		}
		List<User> users = userMapper.selectByExample(example);
		if(users==null||users.isEmpty()){
			return null;
		}
		User u = users.get(0);
		return u;
	}

}
